package org.manusoft.refill.dao;

import java.util.List;
import java.util.Map;

import javax.persistence.Query;

import org.manusoft.refill.domain.TVehicleDetailsRf;
import org.springframework.stereotype.Repository;

@Repository
public class VehicleDAOImpl extends AbstractGenericJPADAO<TVehicleDetailsRf, Integer> implements VehicleDAO{
	
		public TVehicleDetailsRf findByRegNum(String regNum) {
			TVehicleDetailsRf vehicleDetailsRf = null;
			Query query = getEntityManager().createQuery("Select m from TVehicleDetailsRf m where m.vehCharRegno = :regNum");
			query.setParameter("regNum", regNum );
			List<TVehicleDetailsRf> list = query.getResultList();
			if(!org.springframework.util.CollectionUtils.isEmpty(list)){
				vehicleDetailsRf = list.get(0);
			}
			return vehicleDetailsRf;
		}
		
		 public List<TVehicleDetailsRf> loadLazy(int first, int pageSize, String sortField, String sortOrder, Map<String, String> filters){
		        
		        String where = "";
		        for (Map.Entry<String, String> e : filters.entrySet())
		            where += (where.length()>0 ? " AND " : "") + e.getKey() + " like '" + e.getValue() + "%'";
		            
		        Query lazy = getEntityManager().createQuery("Select m from TVehicleDetailsRf m" + (where.length() > 0 ? " where " +  where : "") + (sortField != null && sortOrder != null ? " order by " + sortField + " " + sortOrder : "") );
		        lazy.setFirstResult(first);
		        lazy.setMaxResults(pageSize);
		        
		        return lazy.getResultList();
		    }

		    
		    public Long getRowCount(Map<String, String> filters) {
		        String where = "";
		        if(filters != null) {
		            for (Map.Entry<String, String> e : filters.entrySet()) {
		                where += (where.length()>0 ? " AND " : "") + e.getKey() + " like '" + e.getValue() + "%'";
		            } 
		        }
		        
		        return (Long)this.getEntityManager().createQuery("select count(*) from TVehicleDetailsRf m" + (where.length() > 0 ? " where " +  where : "")).getSingleResult();
		    }
		    
		    public List<TVehicleDetailsRf> findByRegNumAutoComplete(String regNum) {
				Query query = getEntityManager().createQuery("Select m from TVehicleDetailsRf m where m.vehCharRegno LIKE :regNum");
				query.setParameter("regNum", regNum + "%");

				return query.getResultList();
			}

}